package com.tms.service.impl;

import com.tms.domain.Position;
import com.tms.mapper.develop.PositionMapper;
import com.tms.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

/**
 * 职位业务实现
 *
 * @author ozj
 */
@Service
public class PositionServiceImpl implements PositionService {

    @Autowired
    private PositionMapper positionMapper;

    @Override
    @Cacheable(cacheNames = "positions", key = "#id", unless = "#result == null")
    public Position findPositionById(Integer id) {
        return positionMapper.selectByPrimaryKey(id);
    }

    @Override
    @Cacheable(cacheNames = "positions", key = "#name", unless = "#result == null")
    public Position findPositionByName(String name) {
        return positionMapper.selectByName(name);
    }

    @Override
    @Caching(
            put = {
                    @CachePut(cacheNames = "positions", key = "#result.id", unless = "#result == null || #result.id == 0"),
                    @CachePut(cacheNames = "positions", key = "#position.name", unless = "#result == null || #result.id == 0")
            }
    )
    public Position createPosition(Position position) {
        positionMapper.insertSelective(position);
        return position;
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "positions", key = "#position.id"),
                    @CacheEvict(cacheNames = "positions", key = "#position.name")
            }
    )
    public void deletePositionById(Position position) {
        positionMapper.deleteByPrimaryKey(position.getId());
    }

    @Override
    @Caching(
            put = {
                    @CachePut(cacheNames = "positions", key = "#position.id", unless = "#result == null"),
                    @CachePut(cacheNames = "positions", key = "#position.name", unless = "#result == null")
            }
    )
    public Position updatePositionById(Position position) {
        int result = positionMapper.updateByPrimaryKeySelective(position);
        if (result == 0) {
            throw new RuntimeException("更新失败，更新结果数为0");
        }
        return position;
    }
}